<?php
#require_once('TVB/pms/pdes/common/util/ArrayDiff.class.php');
#require_once 'TVB/pms/pdes/common/util/ProofreadSend.php';

class P_EpisodeGetAction extends BaseAction 
{
	public $id;
	public $step;
	public $act;
	public $unpublish;
	public $error_code;

	public $ut;
	public $from;

	public function execute(){
		if(!is_null($this->error_code))
		{
			$this->addError('Episode.Proof read', array($this->error_code, 'Episode.Proof read'));	
		}

		try
		{
			# add episode publish log
			$this->setData("publishLog", publish_log::getPublishLog('episode', $this->id));
            $this->setData('special_operation_premium', TRUE);

			if(!empty($this->unpublish)) {Model::$dbo['r'] = CommonUtils::getDbConn(0,'preview');}

			//highlight init
			$this->highlight('episode', $this->id, $this->act);

			//episode detail 
			$episode = new p_episode();
            $episode_detail = $episode->getDetails($this->id);
			
			$episodeObjects  = $episode_detail->episode_language;
            $episodeArray   = Model::object2array($episodeObjects);
           
            $episode_detail->title     = isset($episodeArray[1]['title']) ? $episodeArray[1]['title']: '';
            $episode_detail->title_en  = isset($episodeArray[2]['title']) ? $episodeArray[2]['title']: '';

			$episode_detail->description  = isset($episodeArray[1]['description']) ? $episodeArray[1]['description']: '';
			$episode_detail->description_en  = isset($episodeArray[2]['description']) ? $episodeArray[2]['description']: '';

			$episode_detail->description_short  = isset($episodeArray[1]['description_short']) ? $episodeArray[1]['description_short']: '';
			$episode_detail->description_short_en = isset($episodeArray[2]['description_short']) ? $episodeArray[2]['description_short']: '';
           
            $episode_detail->average_rating = ($episode_detail->average_rating != 0) ? $episode_detail->average_rating : '';
			$episode_detail->onair_episode_no = ($episode_detail->onair_episode_no != 0) ? $episode_detail->onair_episode_no : '';
			$episode_detail->original_episode_no = ($episode_detail->original_episode_no != 0) ? $episode_detail->original_episode_no : '';
			$episode_detail->publish_datetime = CommonUtils::formatDate($episode_detail->publish_datetime);
			$episode_detail->expire_datetime  = CommonUtils::formatDate($episode_detail->expire_datetime);
			$episode_detail->first_time_onair = CommonUtils::formatDate($episode_detail->first_time_onair);
			
			$episode_detail->episode_language[2]->editor_message = isset($episodeArray[2]['editor_message']) ? $episodeArray[2]['editor_message'] : '';
            
            $this->setData("episode", $episode_detail);
			//programme detail
			$programme = new p_programme();
			$programme_detail = $programme->getDetails($episode_detail->programme_id);
			$programme_name = explode("\n\t",$programme_detail->mix_programme_name);
			$programme_detail->zh_programme_name = $programme_name[0];
			$programme_detail->en_programme_name = $programme_name[1];
			$this->setData("programme", $programme_detail);

			// image/video folder list
			$image_folder_list = array();
			$image_folders = array();
			if (!empty($episode_detail->folders))
			{
				$folder = new p_folder();
				$all_folder = $folder->findByInSql($episode_detail->folders);

				$is_published = CommonUtils::is_published('episode',$this->id);
				foreach ($all_folder as $single_folder)
				{
					$item_list = $folder->get_folder_items($single_folder['id']);
					if (!empty($item_list))
					{
						foreach ($item_list as &$item)
						{
							$item['title'] = 'ID:' . $item['id'] . '<br />' 
								. htmlentities($item['title'], ENT_QUOTES, 'UTF-8');
							$item['status'] = '';
							$item['flag'] = null;
						}
					}
					$folders = array(
						'fid'	=> $single_folder['id'],
						'fspec'	=> $single_folder['folder_type_id'],
						'total'	=> $single_folder['total'],
						'ftype'	=> $single_folder['folder_item_type_id'],
                        'path' => $single_folder['path'],
						'fname'	=> htmlentities($single_folder['system_label'], ENT_QUOTES, 'UTF-8'),
                        'items'	=> $item_list,
					);

					if ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_IMAGE)
					{
						$image_folders[] = $folders;
					}
				}
				$image_folder_list = array('pid'=>$episode_detail->id,'ptype'=>'episode','folders'=>$image_folders);
			}
			$this->setData("image_folder_list", $image_folder_list);

			/**
			// image/video folder list
			$video_folder_list = array();
			$image_folder_list = array();
			$video_folders = array();
			$image_folders = array();
			if (!empty($episode_detail->folders))
			{
				$folder = new folder();
				$all_folder = $folder->findByInSql($episode_detail->folders);

				$diff = $this->_data['diff_folder'];
				$is_published = CommonUtils::is_published('episode',$this->id);
				foreach ($all_folder as $single_folder)
				{
					if ($this->act == 'view' && !$this->unpublish)
					{
						$folders = CommonUtils::getDiffFolderItem($single_folder,$this->act,$diff, $this->unpublish,$is_published);
					}
					else
					{
						$item_list = $folder->get_folder_items($single_folder['id']);
						if (!empty($item_list))
						{
							foreach ($item_list as &$item)
							{
								$item['title'] = 'ID:' . $item['id'] . '<br />' 
												  . htmlentities($item['title'], ENT_QUOTES, 'UTF-8');
								$item['status'] = '';
								$item['flag'] = null;
							}
						}
						$folders = array(
										'fid'	=> $single_folder['id'],
										'fspec'	=> $single_folder['folder_type_id'],
										'total'	=> $single_folder['total'],
										'ftype'	=> $single_folder['folder_item_type_id'],
										'fname'	=> htmlentities($single_folder['system_label'], ENT_QUOTES, 'UTF-8'),
										'items'	=> $item_list
									);
					}

					if ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_VIDEO)
					{
						$video_folders[] = $folders;
					}
					elseif ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_IMAGE)
					{
						$image_folders[] = $folders;
					}
				}
				$video_folder_list = array('pid'=>$episode_detail->id,'ptype'=>'episode','folders'=>$video_folders);
				$image_folder_list = array('pid'=>$episode_detail->id,'ptype'=>'episode','folders'=>$image_folders);
			}
			$this->setData("video_folder_list", $video_folder_list);
			$this->setData("image_folder_list", $image_folder_list);
			 */

			//highlight role list
			$cast_role = new cast_role();
			$role_list = $cast_role->findByInSql($episode_detail->highlighted_cast_roles, AC::ROLE_TYPE_CAST);
			//crew role list
			$crew_role_list = $cast_role->findByInSql($episode_detail->highlighted_cast_roles, AC::ROLE_TYPE_CREW);

			$cast_role_id = array();
			$arr_cast = array();
			foreach ($role_list as $cast)
			{
				$cast_role_id[] = $cast->id;
				$arr_cast[$cast->id] = $cast->system_label;
			}

			//crew role list
			$crew_role_id = array();
			$arr_crew = array();
			foreach ($crew_role_list as $crew)
			{
				$crew_role_id[] = $crew->id;
				$arr_crew[$crew->id] = $crew->system_label;
			}
			$this->setData("arr_cast", $arr_cast);
			$this->setData("arr_crew", $arr_crew);

			//cast list
			$this->handle_cast_crew($cast_role_id, $crew_role_id);
			//$this->handle_cast_crew($cast_role_id, $crew_role_id, "remote");
		/*
		if (!empty($this->_data['publishLog']))
		{
			$this->cast_highlight($cast_role_id, $crew_role_id);
		}
		 */

			$this->setData("id", $this->id);
			$this->setData("type", 'episode');
			$this->setData("step", $this->step);
			$this->setData("act", $this->act);
			$this->setData("unpublish", $this->unpublish);
			$this->setData("from", $this->from);

			$this->make_diff('episode', $this->id, $this->act, $episode_detail);

			return 'succ';
		}
		catch(Exception $e)
		{
			error_log("episode get: {$this->id}" . var_export($e,1));

			$this->emptyData();
			return 'system-error';
		}
	}    

	/**
	 * highlight modify field
	 */
	public function make_diff($type, $id, $act, $episode)
	{
		/*
		if ($act == 'view')
		{
			$diff = $this->_data['diff_other'];
			$highlight = $diff['episode'][$id];
			$highlight['title'] = isset($diff['episode-language'][$id.'1']['title']) ? $diff['episode-language'][$id.'1']['title'] : false;
			$highlight['title_en'] = isset($diff['episode-language'][$id.'2']) ?  $diff['episode-language'][$id.'2']['title'] : false;
			$highlight = array_merge($highlight, $diff['episode-language'][$id.'1']);
			$this->setData('episode_diff', $highlight);
		}
		elseif ($act == 'edit' || $act == 'add')
		{
			$diff = array_fill_keys(array_keys(Model::object2array($episode)), false);
			$this->setData("episode_diff", $diff);
		}
		 */
		$diff = array_fill_keys(array_keys(Model::object2array($episode)), false);
		$this->setData("episode_diff", $diff);
	}

	/**
	 * highlight init handle
	 */
	public function highlight($type, $id, $act)
	{
		// modified by vanni at 2010-04-06 for bug:3686
		return true;

		$db_local =  CommonUtils::getDbConn()->getDbHandle();
		$db_remote =  CommonUtils::getDbConn(0, 'preview')->getDbHandle();

		$proof = new ProofreadSend();
		$local_arr = $proof->getProofreadData($db_local, $type, $id); 
		$remote_arr = $proof->getProofreadData($db_remote, $type, $id); 
		$diff_folder = ArrayDiff::multi_diff($local_arr, $remote_arr);
		if ($act == 'view')
		{
			$diff_other = ArrayDiff::array_diff($local_arr, $remote_arr, $diff_folder);
			$this->setData("diff_other", $diff_other);
		}
		//$remote_casts = isset($remote_arr['episode'][0]) ? $remote_arr['episode'][0]['casts'] : json_encode(array());
		//$this->setData('remote_casts', $remote_casts);
		$this->setData("diff_folder", $diff_folder);
	}

	/**
	 * handle cast/crew data
	 */
	public function handle_cast_crew($cast_role_id, $crew_role_id, $type="")
	{
		$json_cast_list = array();
		if ($type == 'remote')
		{
			$json_cast_list = json_decode($this->_data['remote_casts'], true);
		}
		else
		{
			$json_cast_list = json_decode($this->_data['episode']->casts, true);
		}

		$cast_list = array();
		$crew_list = array();
		if (!empty($json_cast_list))
		{
			foreach ($json_cast_list as $role_id=>$list)
			{
				if (in_array($role_id, $cast_role_id))
				{
					$cast_list[$role_id] = $list;
				}
				elseif (in_array($role_id, $crew_role_id))
				{
					$crew_list[$role_id] = $list;
				}
			}
		}
		else
		{
			$cast_list = array();
			$crew_list = array();
		}

		$this->setData($type."cast_list", $cast_list);
		$this->setData($type."crew_list", $crew_list);
	}

	/**
	 * highlight cast/crew data
	 */
	public function cast_highlight($cast_role_id, $crew_role_id)
	{
		$cast_list = $this->_data['cast_list'];
		$crew_list = $this->_data['crew_list'];
		$remote_cast_list = $this->_data['remotecast_list'];
		$remote_crew_list = $this->_data['remotecrew_list'];

		$highlight_cast = array();
		$highlight_crew = array();
		if (!empty($cast_list))
		{
			$this->compare_cast_crew($cast_list, $remote_cast_list, $cast_role_id, 'cast');
		}
		if (!empty($crew_list))
		{
			$this->compare_cast_crew($crew_list, $remote_crew_list, $crew_role_id, 'crew');
		}
	}

	/**
	 * compare cast/crew data
	 */
	public function compare_cast_crew($cast_list, $remote_cast_list, $cast_role_id, $type)
	{
		$h_object = "highlight_".$type;
		$compare_data = array();
		foreach ($cast_role_id as $role_id)
		{
			//add
			if (isset($cast_list[$role_id]) && !isset($remote_cast_list[$role_id])) 
			{
				$compare_data[$role_id] = true;
			}
			elseif  (isset($cast_list[$role_id]) && isset($remote_cast_list[$role_id])) 
			{
				//modify
				$i = 0;
				$cast_flag = false;
				foreach ($cast_list[$role_id] as $cast_value)
				{
					if (!isset($remote_cast_list[$role_id][$i])) continue;
					$diff_cast = array_diff_assoc($cast_list[$role_id][$i], $remote_cast_list[$role_id][$i]);
					if (!empty($diff_cast))
					{
						$cast_flag = true;
						break;
					}
					$i++;
				}
			
				$compare_data[$role_id] = $cast_flag;
			}
			else
			{
				$compare_data[$role_id] = false;
			}
		}
		$this->setData($h_object, $compare_data);
	}
}
?>
